<template>
  <el-card class="page-container">
    <template #header>
      <div class="header" style="display: flex">
        <div class="title">{{ title }}</div>
      </div>
    </template>
    <el-row>
      <el-col>
        <el-form
          ref="setmealFormRef"
          class="form-inline"
          label-width="120px"
          :model="setmealForm"
          :rules="rules"
          :inline="true"
        >
          <div style="display: flex">
            <el-form-item label="套餐名称:" prop="name">
              <el-input v-model="setmealForm.name" placeholder="请填写套餐名称" />
            </el-form-item>
            <el-form-item label="套餐分类:" prop="categoryName">
              <el-select v-model="setmealForm.categoryId" placeholder="请选择套餐分类">
                <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="套餐价格:" prop="price">
              <el-input v-model="setmealForm.price" placeholder="请设置套餐价格" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="菜品选择:">
              <el-form-item>
                <div class="addDish">
                  <el-button v-if="setmealDishes.length == 0" type="primary" @click="addDish"> 添加菜品 </el-button>
                  <div v-if="setmealDishes.length != 0" class="content">
                    <el-button type="primary" style="margin-bottom: 20px" @click="addDish"> 添加菜品 </el-button>
                    <DishTable :setmeal_dishes="setmealDishes" @delDishHandle="delDishHandle" />
                  </div>
                </div>
                <AddDish
                  ref="addDishRef"
                  v-if="dialogVisible"
                  :dialogVisible="dialogVisible"
                  :setmeal_dishes="setmealDishes"
                  @dialogHandle="dialogHandle"
                  @getCheckList="getCheckList"
                />
              </el-form-item>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="套餐图片:" prop="image">
              <ImgUpload :image="imageUrl" @onImageChange="onImageChange"> </ImgUpload>
            </el-form-item>
          </div>
          <el-form-item label="套餐描述:" prop="description">
            <el-input
              v-model="setmealForm.description"
              :rows="3"
              maxlength="100"
              autosize
              style="width: 350px"
              placeholder="套餐描述,最多100字"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
          <div class="submit">
            <el-form-item>
              <el-button @click="router.back()">取消</el-button>
              <el-button type="primary" @click="saveHandle"> 保存 </el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
<script setup lang="ts">
import DishTable from './components/DishTable.vue'
import AddDish from './components/AddDish.vue'
import { addSetmealAPI, putSetmealAPI } from '@/api/business/setmeal'
import { ref, onMounted, reactive } from 'vue'
import { ElForm, ElMessage, FormRules } from 'element-plus'
import { priceValidator } from '@/utils/validator'
import { CATEGORY_TYPE } from '@/constants'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
// 套餐id
const setmealId = route.query.id as number | null
// 套餐详情信息
import useSetmealDetail from './useSetmealDetail'
const { title, imageUrl, setmealDishes, setmealForm, getSetmeal } = useSetmealDetail(setmealId as number)

// 套餐分类列表
import useCategory from '@/hooks/useCategory'
import { DishListResult } from '@/types/dish'
const { categoryList, getCategorysByType } = useCategory()

onMounted(async () => {
  await Promise.all([getSetmeal(), getCategorysByType(CATEGORY_TYPE.setmeal)])
})
// 表单实例
const setmealFormRef = ref<InstanceType<typeof ElForm> | null>(null)
// 表单校验
const rules = reactive<FormRules<typeof setmealForm>>({
  name: {
    required: true,
    validator: (_rule: any, value: string, callback: Function) => {
      if (!value) {
        callback(new Error('请输入套餐名称'))
      } else {
        const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/
        if (!reg.test(value)) {
          callback(new Error('套餐名称输入不符,请输入2-20个字符'))
        } else {
          callback()
        }
      }
    },
    trigger: 'blur',
  },
  categoryId: {
    required: true,
    message: '请选择套餐分类',
    trigger: 'change',
  },
  image: {
    required: true,
    message: '菜品图片不能为空',
  },
  price: {
    required: true,
    validator: priceValidator,
    trigger: 'blur',
  },
})
const onImageChange = (value: string) => {
  imageUrl.value = value
  setmealForm.value.image = value
}
// 删除dishTable中的菜品
const delDishHandle = (id: number) => {
  const index = setmealDishes.value.findIndex(item => item.id === id)
  setmealDishes.value.splice(index, 1)
}
// 添加菜品弹窗
const dialogVisible = ref(false)
// 添加菜品
const addDish = () => {
  dialogVisible.value = true
}
const dialogHandle = (value: boolean) => {
  dialogVisible.value = value
}
// 获取菜品弹窗中已选择的菜品列表
const getCheckList = (value: DishListResult[]) => {
  // console.log(value)
  const dishTableData = value.map(item => ({
    name: item.name,
    price: item.price,
    dishId: item.id,
    copies: 1,
  }))
  setmealDishes.value = dishTableData
}

// 提交/保存
const saveHandle = () => {
  setmealFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (setmealDishes.value.length === 0) {
        ElMessage.warning('套餐菜品不能为空')
      }
      if (!setmealForm.value.image) {
        ElMessage.warning('套餐图片不能为空')
      }
      let params = {
        ...setmealForm.value,
      } as any
      params.image = imageUrl.value
      params.setmealDishes = setmealDishes.value
      if (title.value === '修改套餐') {
        await putSetmealAPI(params)
        ElMessage.success('修改成功')
        router.back()
      } else if (title.value === '添加套餐') {
        await addSetmealAPI(params)
        ElMessage.success('添加成功')
        router.back()
      }
    } else {
      ElMessage.error('表单校验失败')
    }
  })
}
</script>
<style scoped lang="scss">
.page-container{
  overflow: auto;
}
.submit {
  display: flex;
  justify-content: space-around;
}
.addDish {
  // width: 777px;

  .content {
    background: #fafafb;
    padding: 20px;
    border: solid 1px #d8dde3;
    border-radius: 3px;
  }
}
</style>
